package kaist.sep521.lego.circlebicycle;

import android.os.Bundle;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.os.StrictMode;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

public class MainActivity extends Activity {
	private EditText id;
	private EditText pw;
	public static User myInfo = new User();
	public static String loginUrl = "http://14.63.196.253/~lego/login.php";

	public static boolean testModeFlag = false;

	// Alphabet + Number
	protected InputFilter filterAlphaNum = new InputFilter() {
		public CharSequence filter(CharSequence source, int start, int end,
				Spanned dest, int dstart, int dend) {
			Pattern ps = Pattern.compile("^[a-zA-Z0-9]+$");
			if (!ps.matcher(source).matches()) {
				return "";
			} 
			return null;
		} 
	}; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());

		id = (EditText)findViewById(R.id.main_editID);
		pw = (EditText)findViewById(R.id.main_editPW);
		id.setFilters(new InputFilter[]{filterAlphaNum});
		pw.setFilters(new InputFilter[]{filterAlphaNum});

		final Button login = (Button)findViewById(R.id.main_login_button);
		final Button signup = (Button)findViewById(R.id.main_signup_button);

		// Set up the user interaction to manually show or hide the system UI.
		login.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				// check a validation of user
				String username = id.getText().toString();
				String password = pw.getText().toString();
				String result = login(username, password);

				if (result.equals("true")){ 
					// move to menu window
					setMyInfo(username);
					if(username.matches("test.*")){
						testModeFlag = true;
						Toast.makeText(MainActivity.this, "Test Mode Enabled", Toast.LENGTH_LONG).show();
					}
					//Toast.makeText(MainActivity.this, "Log In success. Welcome "+username+" :)", Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(getBaseContext(), MenuActivity.class);
					startActivity(intent);
					finish();
				}
				else{
					Toast.makeText(MainActivity.this, "Fail to login. Try again!", Toast.LENGTH_LONG).show();
				}
			}
		});

		// Set up the user interaction to manually show or hide the system UI.
		signup.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				// move to registration window
				Intent intent = new Intent(getBaseContext(), RegisterActivity.class);
				startActivity(intent);
			}
		});
	}

	private void setMyInfo(String username) {
		try {
			String xml = "http://14.63.196.253/~lego/userinfo.php?username="+username;
			URL url = new URL(xml);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream is = conn.getInputStream();

				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();
				XMLReader xr = sp.getXMLReader();
				ParserHandler pHandler = new ParserHandler();
				xr.setContentHandler(pHandler);
				xr.parse(new InputSource(is));
				ArrayList<User> mList = pHandler.getParsedData();
				myInfo = mList.get(0);
			} else {
				Toast.makeText(this, "Server connection error!!", Toast.LENGTH_SHORT).show();
			}
			conn.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String login(String username, String password) {

		// Create a new HttpClient and Post Header
		HttpClient httpclient = new DefaultHttpClient();
		Log.e("Responce-->","after httpclient");
		/* login.php returns true if username and password is equal to saranga */
		HttpPost httppost = new HttpPost(loginUrl);
		Log.e("Responce-->","after httppost");
		try {
			// Add user name and password
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("user", username));
			nameValuePairs.add(new BasicNameValuePair("pass", password));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			Log.e("Responce-->","after using the list name pair");

			// Execute HTTP Post Request
			Log.w("SENCIDE", "Execute HTTP Post Request");
			HttpResponse response = httpclient.execute(httppost);
			Log.e("Responce-->","after execute the http response");
			// String str = inputStreamToString(response.getEntity().getContent()).toString();
			String str = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
			//Log.w("SENCIDE", str);
			Log.e("Responce-->",""+str);

			if(str.toString().equalsIgnoreCase("true"))
			{
				Log.w("SENCIDE", "TRUE");
				return("true"); 
			}else
			{
				Log.w("SENCIDE", "FALSE");
				return(str); 
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return("Network Connection Error. Please, check your data network."); 

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		id.setText(null);
		pw.setText(null);
	}
}
